<template>
  <div class="page-todo">
    <div class="page-form">
      <LlForm ref="form" title="新增待办">
        <LlFormItem
          label="申请类型"
          filed="todoTypeName"
          :value="form.todoTypeName"
          :rules="[{ required: true, message: '请选择申请类型' }]"
          @click="() => (showTodoType = true)"
        />
        <!-- showDoUser = true -->
        <LlFormItem
          label="执行人"
          filed="username"
          :value="form.username"
          :rules="[{ required: true, message: '请选择执行人' }]"
          @click="openPopup(1)"
        />
        <LlFormItem
          :label="`预计${titlePrefix}日期`"
          filed="expectTodoDate"
          placehoder="请选择外出时间"
          :value="form.expectTodoDate"
          :rules="[{ required: true, message: '请选择外出时间' }]"
          @click="() => (showVisitTime = true)"
        >
          <template #icon>
            <Icon :name="DateIcon" />
          </template>
        </LlFormItem>
        <LlFormItem
          v-if="form.todoType !== 3"
          :label="`${titlePrefix}商机`"
          filed="businessOpportunity"
          :value="form.businessOpportunity"
          :rules="[{ required: true, message: `请选择${titlePrefix}商家` }]"
          @click="_showVisitMerchant"
        />
        <LlFormItem
          v-if="form.todoType !== 3"
          :label="`${titlePrefix}KP`"
          filed="kp"
          :value="form.kp"
          :rules="[{ required: true, message: `请选择${titlePrefix}KP` }]"
          @click="_showVisitKP"
        />
        <LlFormItem
          :label="`${titlePrefix}地点`"
          filed="address"
          :value="form.address"
          placehoder="请选择"
          :rules="[{ required: true, message: `请选择${titlePrefix}地点` }]"
          @click="() => (showVisitLocation = true)"
        >
          <template #icon>
            <Icon :name="LocationIcon" />
          </template>
        </LlFormItem>
        <LlFormItem
          :label="`${titlePrefix}内容`"
          filed="type"
          :show-arrow="false"
        >
          <Field
            v-model="form.content"
            :rows="contentLength"
            type="textarea"
            autosize
            class="!p-0"
            maxlength="150"
            placeholder="请输入内容"
            show-word-limit
          />
        </LlFormItem>
      </LlForm>
    </div>
    <div class="footer">
      <Button
        class="flex-1 !rounded-10px"
        @click="$router.back()"
        plain
        type="primary"
      >
        取消
      </Button>
      <Button
        @click="handleSave"
        :loading="loading"
        class="flex-1 !ml-9px !rounded-10px"
        type="primary"
      >
        新增
      </Button>
    </div>
    <div class="add__business">
      <!-- 申请类型 -->
      <Popup v-model="showTodoType" round position="bottom">
        <span class="title">申请类型</span>
        <Picker
          :columns="todoTypeOptions"
          show-toolbar
          @cancel="showTodoType = false"
          @confirm="
            (item) =>
              _pickerSelect(item, 'todoType', 'todoTypeName', 'showTodoType')
          "
          default-index="1"
          toolbar-position="bottom"
          swipe-duration="100"
        />
      </Popup>
    </div>

    <div class="add__business">
      <!-- 执行人 -->
      <Popup v-model="showDoUser" round position="bottom">
        <LlSearchPicker
          v-if="showDoUser"
          title="执行人"
          :columns="doUserOptions"
          @search="_doUserLoad"
          @load="_doUserLoad"
          @cancel="showDoUser = false"
          @confirm="_doUserSelect"
          ref="LlSearchPickers"
        />
      </Popup>
    </div>

    <div class="add__business">
      <!-- 外出时间 -->
      <Popup v-model="showVisitTime" round position="bottom">
        <LlDatePicker
          title="拜访时间"
          @cancel="showVisitTime = false"
          :formatter="true"
          @confirm="
            (item) =>
              _pickerSelect(
                { text: item },
                'expectTodoDate',
                'expectTodoDate',
                'showVisitTime'
              )
          "
        />
      </Popup>
    </div>

    <div class="add__business">
      <!-- 拜访商家 -->
      <Popup v-model="showVisitMerchant" round position="bottom">
        <LlSearchPicker
          v-if="showVisitMerchant"
          title="拜访商机"
          :columns="merchantOptions"
          @search="_merchantLoad"
          @load="_merchantLoad"
          @cancel="showVisitMerchant = false"
          @confirm="
            (item) =>
              _pickerSelect(
                item,
                'businessOpportunityId',
                'businessOpportunity',
                'showVisitMerchant'
              )
          "
          ref="LlSearchPickers"
        />
      </Popup>
    </div>

    <div class="add__business">
      <!-- 拜访kp -->
      <Popup v-model="showVisitKP" round position="bottom">
        <span class="title">拜访KP</span>
        <Picker
          :columns="visitKPOptions"
          show-toolbar
          @cancel="showVisitKP = false"
          @confirm="(item) => _pickerSelect(item, 'kpId', 'kp', 'showVisitKP')"
          toolbar-position="bottom"
          swipe-duration="100"
        />
      </Popup>
    </div>

    <!-- 拜访地点 -->
    <Popup v-model="showVisitLocation" position="right">
      <LlMap
        v-if="showVisitLocation"
        @cancel="showVisitLocation = false"
        @confirm="_mapConfirm"
        type="search"
      />
    </Popup>
  </div>
</template>

<script>
import _ from "lodash";
import { Toast, Icon, Field, Button, Popup, Picker } from "vant";
import LlForm from "@/components/ll-form";
import LlFormItem from "@/components/ll-form-item";
import LlDatePicker from "@/components/ll-date-picker";
import LlSearchPicker from "@/components/ll-search-picker";
import LlMap from "@/components/ll-map";
import DateIcon from "@/assets/icon/date.png";
import LocationIcon from "@/assets/icon/location.png";
import { TODO_TYPE } from "@/constants";
import {
  fetchTodoCreate,
  fetchTodoUser,
  fetchTodoBusiness,
  fetchKpList,
} from "@/services";

export default {
  components: {
    Icon,
    Field,
    Button,
    Popup,
    Picker,
    LlForm,
    LlFormItem,
    LlDatePicker,
    LlSearchPicker,
    LlMap,
  },
  data() {
    return {
      DateIcon,
      LocationIcon,
      loading: false,
      form: {
        todoType: null,
        todoTypeName: null,
        userId: null,
        username: null,
        userJobNo: null,
        expectTodoDate: null,
        businessOpportunityId: null, // 拜访商家
        businessOpportunity: null, // 拜访商家名称
        kpId: null,
        kp: null,
        poi: null,
        address: null,
        content: "",
      },
      showTodoType: false, // 申请类型
      todoTypeOptions: TODO_TYPE.map(({ text, key }) => ({
        text: `外出${text}`,
        key,
      })),
      showDoUser: false, // 执行人
      doUserOptions: [],
      showVisitTime: false, // 外出时间
      showVisitMerchant: false, // 拜访商机
      merchantOptions: [],
      showVisitKP: false, // 拜访kp
      visitKPOptions: [],
      showVisitLocation: false, // 拜访地点
    };
  },
  computed: {
    titlePrefix() {
      if (this.form.todoType) {
        const [type] = TODO_TYPE.filter(
          ({ key }) => key === this.form.todoType
        );
        return type.text;
      } else {
        return "拜访";
      }
    },
    contentLength() {
      let content = this.form.content.length;
      let row = 1;
      if (content > 25) {
        row = 1;
      }
      if (content > 50) {
        row = 2;
      }
      if (content > 100) {
        row = 3;
      }
      if (content > 125) {
        row = 4;
      }
      return row;
    },
  },
  methods: {
    handleSave: _.throttle(function () {
      this.$refs.form
        .validate()
        .then(async () => {
          try {
            const form = { ...this.form };
            // 扫街类型没有商家和KP
            if (this.form.todoType === 3) {
              form.businessOpportunityId = null;
              form.businessOpportunity = null;
              form.kpId = null;
              form.kp = null;
            }
            this.loading = true;
            await fetchTodoCreate(form);
            this.loading = false;
            this.$store.commit(`work/set_loadDataWork`, {
              value: true,
            });
            this.$nextTick(() => {
              this.$router.back();
            });
          } catch (error) {
            this.loading = false;
            Toast("新增失败");
          }
        })
        .catch((e) => {
          Toast(e[0].message);
        });
    }, 500),
    /**
     * 执行人远程搜索
     */
    async _doUserLoad(name, pageNum, status) {
      try {
        if (pageNum === 1) {
          this.doUserOptions = [];
          status.finished = false;
        }
        const { data = [], total } = await fetchTodoUser({ name, pageNum });
        const users = data.map(({ userId, name, jobNo }) => ({
          text: name,
          key: userId,
          userJobNo: jobNo,
        }));
        this.doUserOptions = [...this.doUserOptions, ...users];
        if (this.doUserOptions.length >= total) {
          status.finished = true;
        }
        status.loading = false;
      } catch (error) {
        status.loading = false;
        status.finished = true;
        Toast("获取执行人失败");
      }
    },
    _showVisitMerchant() {
      if (this.form.userId) {
        this.showVisitMerchant = true;
        this.$nextTick(() => {
          this.$refs.LlSearchPickers.setValue(this.form.businessOpportunity);
        });
      } else {
        Toast("请选择执行人");
      }
    },
    // 商机远程搜索
    async _merchantLoad(keyword, pageNum, status) {
      // type  1 拜访商机 2 回访商机
      try {
        if (pageNum === 1) {
          this.merchantOptions = [];
        }
        const { data, total } = await fetchTodoBusiness({
          pageNum,
          pageSize: 20,
          belongLib: [3, 4],
          search: keyword,
          userId: this.form.userId,
          type: this.form.todoType,
        });
        const format = data.map(({ id, name }) => {
          return {
            text: name,
            key: id,
          };
        });
        this.merchantOptions = [...this.merchantOptions, ...format];
        if (this.merchantOptions.length >= total) {
          status.finished = true;
        }
        status.loading = false;
      } catch (error) {
        status.loading = false;
        status.finished = true;
        Toast("商机加载失败");
      }
    },
    /**
     * kp
     */
    async _showVisitKP() {
      try {
        if (this.form.businessOpportunityId) {
          const result = await fetchKpList({
            boId: this.form.businessOpportunityId,
          });
          this.visitKPOptions = result.map(({ name, id }) => ({
            text: name,
            key: id,
          }));
          this.$nextTick(() => {
            this.showVisitKP = true;
          });
        } else {
          Toast("请选择商机");
        }
      } catch (error) {
        Toast("KP加载失败");
      }
    },
    _doUserSelect(item) {
      if (this.form.username != item.text) {
        this.form.businessOpportunity = null;
        this.form.kp = null;
      }
      this.form.userId = item.key;
      this.form.username = item.text;
      this.form.userJobNo = item.userJobNo;
      this.$nextTick(() => {
        this.showDoUser = false;
      });
    },
    /**
     * val 选中的值
     * key 表单的key
     * model popup的model
     */
    _pickerSelect(val, value, label, model) {
      if (
        value === "businessOpportunityId" &&
        this.form.businessOpportunity != val.text
      ) {
        this.form.kp = null;
      }
      this.form[value] = val.key;
      this.form[label] = val.text;
      console.log(this.form);
      this.$nextTick(() => {
        this[model] = false;
      });
    },
    _mapConfirm(poi) {
      this.form.address = `${poi.pname}${poi.cityname}${poi.adname}${poi.address}(${poi.name})`;
      this.form.poi = poi.id;
      this.$nextTick(() => {
        this.showVisitLocation = false;
      });
    },
    openPopup(val) {
      if (val === 1) {
        // 执行人
        this.showDoUser = true;
        this.$nextTick(() => {
          this.$refs.LlSearchPickers.setValue(this.form.username);
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.page-todo {
  @apply flex flex-col;
  .page-form {
    @apply px-10px py-12px  flex-1 overflow-auto;
  }
  .footer {
    @apply flex items-center pt-10px px-16px bg-white;
    padding-bottom: calc(env(safe-area-inset-bottom) + 10px);
    box-shadow: 0px -2px 6px 0px rgba(164, 170, 183, 0.2);
  }
}
.add__business {
  width: 100%;
  .van-popup {
    padding-top: 20px; // 12px 0 12px
    .title {
      margin-left: 12px;
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
      margin-bottom: 12px;
    }
    .van-picker {
      padding: 0 16px;
    }
    .van-picker__columns {
      padding: 0 12px;
    }
    ::v-deep .van-picker__toolbar {
      box-shadow: 0px -1px 1px 0px #f5f5f5;
      height: calc(50px + env(safe-area-inset-bottom));
      // min-height: 50px;
      padding-bottom: env(safe-area-inset-bottom);
      padding-top: 10px;
    }
    ::v-deep .van-picker__cancel,
    ::v-deep .van-picker__confirm {
      flex-grow: 1;
      // min-width: 28px;
      height: 100%;
      font-weight: 500;
      text-align: center;
      font-size: 14px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
    }
    ::v-deep .van-picker__cancel {
      color: #666666;
    }
    ::v-deep .van-picker__cancel::after {
      content: "";
      position: absolute;
      display: inline-block;
      width: 1px;
      height: 5.33333vw;
      background: #f0f0f0;
      left: 50%;
    }
    ::v-deep .van-picker__confirm {
      color: #1d6fe9;
    }
    ::v-deep .van-picker-column__item {
      // height: 52px !important;
      .van-ellipsis {
        color: #c5cad5;
        font-size: 14px;
      }
    }
    ::v-deep .van-picker-column__item--selected {
      .van-ellipsis {
        color: #1d6fe9;
        font-weight: 500;
      }
    }
    ::v-deep .van-field__body {
      word-break: break-all;
    }
    ::v-deep .toolbar__title {
      font-size: 16px;
      font-family: PingFangSC-Medium, PingFang SC;
      font-weight: 500;
      color: #333333;
    }
    ::v-deep {
      .van-search {
        padding: 0;
        .van-search__content {
          padding: 0;
        }
      }
    }
  }
}
</style>
